package org.hamster.common.puremvc.proxies
{
	import flash.net.URLRequestMethod;
	
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import org.hamster.common.services.LoadingMaskService;
	import org.hamster.common.utils.StringUtil;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	public class BaseRemoteProxy extends Proxy
	{
		public static const REMOTE_SERVICE_LOAD_FAULT:String = "remoteServiceLoadFault";
		
		public static var gResultFormat:String = "e4x";
		
		public static function initConfig(resultFormat:String):void
		{
			gResultFormat = resultFormat;
		}
		
		public var loadingText:String;
		
		public function BaseRemoteProxy(proxyName:String=null, loadingText:String = null)
		{
			super(proxyName, null);
			
			this.loadingText = loadingText;
		}
		
		public function load(url:String, params:Object = null, method:String = "POST", resultFormat:String = null):void
		{
			var httpService:HTTPService = new HTTPService();
			httpService.method = method;
			httpService.url = url;
			httpService.resultFormat = StringUtil.isEmpty(resultFormat) ? gResultFormat : resultFormat;
			httpService.addEventListener(ResultEvent.RESULT, 	httpResultHandler);
			httpService.addEventListener(FaultEvent.FAULT, 		httpFaultHandler);
			httpService.send(params);
			
			if (!StringUtil.isEmpty(loadingText)) {
				LoadingMaskService.instance.show(loadingText);
			}
		}
		
		private function httpResultHandler(event:ResultEvent):void
		{
			if (!StringUtil.isEmpty(loadingText)) {
				LoadingMaskService.instance.hide();
			}
			
			processResultHandler(event.result);
		}
		
		private function httpFaultHandler(event:FaultEvent):void
		{
			if (!StringUtil.isEmpty(loadingText)) {
				LoadingMaskService.instance.hide();
			}	
			
			processFaultHandler(event.fault);
		}
		
		protected function processResultHandler(data:Object):void
		{
			
		}
		
		protected function processFaultHandler(fault:Fault):void
		{
			this.sendNotification(REMOTE_SERVICE_LOAD_FAULT, fault);
		}
	}
}